<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>麻将记钱器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link
      href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css"
      rel="stylesheet"
    />
    <script>
      tailwind.config = {
        theme: {
          extend: {
            colors: {
              primary: "#3B82F6",
              secondary: "#F97316",
              neutral: "#1F2937",
              success: "#10B981",
              danger: "#EF4444",
            },
            fontFamily: {
              sans: ["Inter", "system-ui", "sans-serif"],
            },
          },
        },
      };
    </script>
    <style type="text/tailwindcss">
      @layer utilities {
        .content-auto {
          content-visibility: auto;
        }
        .card-shadow {
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        }
        .btn-hover {
          @apply transition-all duration-300 hover:shadow-lg transform hover:-translate-y-0.5;
        }
        .input-focus {
          @apply focus:ring-2 focus:ring-primary/50 focus:border-primary;
        }
      }
    </style>
  </head>
  <body class="bg-gray-50 min-h-screen font-sans">
    <div class="max-w-5xl mx-auto px-4 py-8">
      <header class="mb-10 text-center">
        <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-neutral mb-2">
          麻将记钱器
        </h1>
      </header>

      <main class="space-y-8">
        <!-- 修改昵称表单 -->
        <div class="bg-white rounded-xl p-6 card-shadow">
          <h2 class="text-xl font-semibold mb-4 flex items-center">
            <i class="fa fa-user text-primary mr-2"></i>
            修改玩家昵称
          </h2>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-gray-700 mb-2">玩家1昵称</label>
              <input
                type="text"
                id="player1Nickname"
                class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus"
                placeholder="输入昵称"
              />
            </div>
            <div>
              <label class="block text-gray-700 mb-2">玩家2昵称</label>
              <input
                type="text"
                id="player2Nickname"
                class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus"
                placeholder="输入昵称"
              />
            </div>
            <div>
              <label class="block text-gray-700 mb-2">玩家3昵称</label>
              <input
                type="text"
                id="player3Nickname"
                class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus"
                placeholder="输入昵称"
              />
            </div>
            <div>
              <label class="block text-gray-700 mb-2">玩家4昵称</label>
              <input
                type="text"
                id="player4Nickname"
                class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus"
                placeholder="输入昵称"
              />
            </div>
          </div>
          <div class="mt-6">
            <button
              id="updateNicknames"
              class="bg-primary hover:bg-primary/90 text-white py-3 px-6 rounded-lg font-medium btn-hover"
            >
              <i class="fa fa-save mr-2"></i>
              保存昵称
            </button>
          </div>
        </div>

        <!-- 记钱方式选择 -->
        <div class="bg-white rounded-xl p-6 card-shadow">
          <h2 class="text-xl font-semibold mb-4 flex items-center">
            <i class="fa fa-calculator text-primary mr-2"></i>
            选择记钱方式
          </h2>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <button
              id="equalBtn"
              class="bg-primary text-white py-4 px-6 rounded-lg text-lg font-medium flex items-center justify-center btn-hover"
            >
              <i class="fa fa-users mr-2"></i>
              均等支付
            </button>
            <button
              id="unequalBtn"
              class="bg-secondary text-white py-4 px-6 rounded-lg text-lg font-medium flex items-center justify-center btn-hover"
            >
              <i class="fa fa-user-circle mr-2"></i>
              不同金额支付
            </button>
          </div>
        </div>

        <!-- 均等支付表单 -->
        <div id="equalForm" class="hidden bg-white rounded-xl p-6 card-shadow">
          <h2 class="text-xl font-semibold mb-4 flex items-center">
            <i class="fa fa-money text-primary mr-2"></i>
            均等支付记录
          </h2>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-gray-700 mb-2">赢家</label>
              <select
                id="equalWinner"
                class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus"
              >
                <option value="player1">玩家1</option>
                <option value="player2">玩家2</option>
                <option value="player3">玩家3</option>
                <option value="player4">玩家4</option>
              </select>
            </div>

            <div>
              <label class="block text-gray-700 mb-2">每人支付金额</label>
              <div class="relative">
                <span
                  class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500"
                  >¥</span
                >
                <input
                  type="number"
                  id="equalAmount"
                  class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg input-focus"
                  placeholder="输入金额"
                />
              </div>
            </div>
          </div>

          <div class="mt-6">
            <button
              id="addEqualRecord"
              class="bg-primary hover:bg-primary/90 text-white py-3 px-6 rounded-lg font-medium btn-hover"
            >
              <i class="fa fa-plus-circle mr-2"></i>
              添加记录
            </button>
          </div>
        </div>

        <!-- 不同金额支付表单 -->
        <div
          id="unequalForm"
          class="hidden bg-white rounded-xl p-6 card-shadow"
        >
          <h2 class="text-xl font-semibold mb-4 flex items-center">
            <i class="fa fa-money text-secondary mr-2"></i>
            不同金额支付记录
          </h2>

          <div class="mb-4">
            <label class="block text-gray-700 mb-2">赢家</label>
            <select
              id="unequalWinner"
              class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus"
            >
              <option value="player1">玩家1</option>
              <option value="player2">玩家2</option>
              <option value="player3">玩家3</option>
              <option value="player4">玩家4</option>
            </select>
          </div>

          <div id="payerInputs" class="space-y-4 mb-6">
            <!-- 玩家1支付金额 -->
            <div
              id="player1Input"
              class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center"
            >
              <div class="md:col-span-1">
                <label class="block text-gray-700">玩家1支付</label>
              </div>
              <div class="md:col-span-3 relative">
                <span
                  class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500"
                  >¥</span
                >
                <input
                  type="number"
                  id="player1Amount"
                  class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg input-focus"
                  placeholder="输入金额"
                />
              </div>
            </div>

            <!-- 玩家2支付金额 -->
            <div
              id="player2Input"
              class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center"
            >
              <div class="md:col-span-1">
                <label class="block text-gray-700">玩家2支付</label>
              </div>
              <div class="md:col-span-3 relative">
                <span
                  class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500"
                  >¥</span
                >
                <input
                  type="number"
                  id="player2Amount"
                  class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg input-focus"
                  placeholder="输入金额"
                />
              </div>
            </div>

            <!-- 玩家3支付金额 -->
            <div
              id="player3Input"
              class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center"
            >
              <div class="md:col-span-1">
                <label class="block text-gray-700">玩家3支付</label>
              </div>
              <div class="md:col-span-3 relative">
                <span
                  class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500"
                  >¥</span
                >
                <input
                  type="number"
                  id="player3Amount"
                  class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg input-focus"
                  placeholder="输入金额"
                />
              </div>
            </div>

            <!-- 玩家4支付金额 -->
            <div
              id="player4Input"
              class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center"
            >
              <div class="md:col-span-1">
                <label class="block text-gray-700">玩家4支付</label>
              </div>
              <div class="md:col-span-3 relative">
                <span
                  class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500"
                  >¥</span
                >
                <input
                  type="number"
                  id="player4Amount"
                  class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg input-focus"
                  placeholder="输入金额"
                />
              </div>
            </div>
          </div>

          <div class="mt-6">
            <button
              id="addUnequalRecord"
              class="bg-secondary hover:bg-secondary/90 text-white py-3 px-6 rounded-lg font-medium btn-hover"
            >
              <i class="fa fa-plus-circle mr-2"></i>
              添加记录
            </button>
          </div>
        </div>

        <!-- 记录列表 -->
        <div class="bg-white rounded-xl p-6 card-shadow">
          <h2 class="text-xl font-semibold mb-4 flex items-center">
            <i class="fa fa-history text-neutral mr-2"></i>
            记录列表
          </h2>

          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50">
                <tr>
                  <th
                    scope="col"
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    类型
                  </th>
                  <th
                    scope="col"
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    赢家
                  </th>
                  <th
                    scope="col"
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    支付情况
                  </th>
                  <th
                    scope="col"
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    总金额
                  </th>
                  <th
                    scope="col"
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    时间
                  </th>
                  <th
                    scope="col"
                    class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    操作
                  </th>
                </tr>
              </thead>
              <tbody id="recordList" class="bg-white divide-y divide-gray-200">
                <!-- 记录将通过JavaScript动态添加 -->
                <tr class="text-center">
                  <td colspan="6" class="px-6 py-10 text-gray-500">暂无记录</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div class="mt-6 flex justify-end">
            <button
              id="clearRecords"
              class="bg-gray-200 hover:bg-gray-300 text-gray-800 py-2 px-4 rounded-lg font-medium btn-hover"
            >
              <i class="fa fa-trash mr-2"></i>
              清空记录
            </button>
          </div>
        </div>

        <!-- 结算结果 -->
        <div class="bg-white rounded-xl p-6 card-shadow">
          <h2 class="text-xl font-semibold mb-4 flex items-center">
            <i class="fa fa-calculator text-success mr-2"></i>
            结算结果
          </h2>

          <div
            id="resultContainer"
            class="grid grid-cols-1 md:grid-cols-2 gap-6"
          >
            <!-- 玩家1结果 -->
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="font-medium text-lg mb-2 flex items-center">
                <span
                  class="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center mr-2"
                >
                  <i class="fa fa-user text-primary"></i>
                </span>
                <span id="player1Name">玩家1</span>
              </h3>
              <p id="player1Result" class="text-xl font-semibold">¥0</p>
            </div>

            <!-- 玩家2结果 -->
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="font-medium text-lg mb-2 flex items-center">
                <span
                  class="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center mr-2"
                >
                  <i class="fa fa-user text-primary"></i>
                </span>
                <span id="player2Name">玩家2</span>
              </h3>
              <p id="player2Result" class="text-xl font-semibold">¥0</p>
            </div>

            <!-- 玩家3结果 -->
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="font-medium text-lg mb-2 flex items-center">
                <span
                  class="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center mr-2"
                >
                  <i class="fa fa-user text-primary"></i>
                </span>
                <span id="player3Name">玩家3</span>
              </h3>
              <p id="player3Result" class="text-xl font-semibold">¥0</p>
            </div>

            <!-- 玩家4结果 -->
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="font-medium text-lg mb-2 flex items-center">
                <span
                  class="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center mr-2"
                >
                  <i class="fa fa-user text-primary"></i>
                </span>
                <span id="player4Name">玩家4</span>
              </h3>
              <p id="player4Result" class="text-xl font-semibold">¥0</p>
            </div>
          </div>

          <div class="mt-6 flex justify-end">
            <button
              id="exportResult"
              class="bg-success hover:bg-success/90 text-white py-3 px-6 rounded-lg font-medium btn-hover"
            >
              <i class="fa fa-download mr-2"></i>
              导出结果
            </button>
          </div>
        </div>
      </main>

      <footer class="mt-12 text-center text-gray-500 text-sm">
        <p>飞翔麻将记钱器 | 看看谁在输钱</p>
      </footer>
    </div>

    <!-- 通知组件 -->
    <div
      id="notification"
      class="fixed top-4 right-4 p-4 rounded-lg shadow-lg transform transition-all duration-500 ease-in-out translate-x-full opacity-0 z-50"
    >
      <div class="flex items-center">
        <i id="notificationIcon" class="fa mr-2"></i>
        <span id="notificationText"></span>
      </div>
    </div>

    <script>
      // 玩家数据
      const players = {
        player1: { name: "玩家1", balance: 0 },
        player2: { name: "玩家2", balance: 0 },
        player3: { name: "玩家3", balance: 0 },
        player4: { name: "玩家4", balance: 0 },
      };

      // 记录数组
      let records = [];

      // DOM 元素
      const equalBtn = document.getElementById("equalBtn");
      const unequalBtn = document.getElementById("unequalBtn");
      const equalForm = document.getElementById("equalForm");
      const unequalForm = document.getElementById("unequalForm");
      const addEqualRecord = document.getElementById("addEqualRecord");
      const addUnequalRecord = document.getElementById("addUnequalRecord");
      const recordList = document.getElementById("recordList");
      const clearRecords = document.getElementById("clearRecords");
      const exportResult = document.getElementById("exportResult");
      const notification = document.getElementById("notification");
      const notificationText = document.getElementById("notificationText");
      const notificationIcon = document.getElementById("notificationIcon");
      const unequalWinner = document.getElementById("unequalWinner");
      const player1Input = document.getElementById("player1Input");
      const player2Input = document.getElementById("player2Input");
      const player3Input = document.getElementById("player3Input");
      const player4Input = document.getElementById("player4Input");
      const player1Nickname = document.getElementById("player1Nickname");
      const player2Nickname = document.getElementById("player2Nickname");
      const player3Nickname = document.getElementById("player3Nickname");
      const player4Nickname = document.getElementById("player4Nickname");
      const updateNicknames = document.getElementById("updateNicknames");
      const player1Name = document.getElementById("player1Name");
      const player2Name = document.getElementById("player2Name");
      const player3Name = document.getElementById("player3Name");
      const player4Name = document.getElementById("player4Name");
      const equalWinnerSelect = document.getElementById("equalWinner");
      const unequalWinnerSelect = document.getElementById("unequalWinner");

      // 检查昵称是否重复
      function checkDuplicateNicknames() {
        const nicknames = [
          player1Nickname.value.trim() || "玩家1",
          player2Nickname.value.trim() || "玩家2",
          player3Nickname.value.trim() || "玩家3",
          player4Nickname.value.trim() || "玩家4",
        ];

        // 使用 Set 检查重复
        const uniqueNicknames = new Set(nicknames);
        if (nicknames.length !== uniqueNicknames.size) {
          // 找出重复的昵称
          const duplicates = nicknames.filter((name, index) => {
            return nicknames.indexOf(name) !== index;
          });

          showNotification(
            `不能使用重复的昵称：${[...new Set(duplicates)].join("、")}`,
            "error"
          );
          return true;
        }

        return false;
      }

      // 更新选择框中的玩家名称
      function updatePlayerNamesInSelects() {
        equalWinnerSelect.innerHTML = `
          <option value="player1">${players.player1.name}</option>
          <option value="player2">${players.player2.name}</option>
          <option value="player3">${players.player3.name}</option>
          <option value="player4">${players.player4.name}</option>
        `;

        unequalWinnerSelect.innerHTML = `
          <option value="player1">${players.player1.name}</option>
          <option value="player2">${players.player2.name}</option>
          <option value="player3">${players.player3.name}</option>
          <option value="player4">${players.player4.name}</option>
        `;

        // 更新输入框标签
        document.querySelector(
          "#player1Input label"
        ).textContent = `${players.player1.name}支付`;
        document.querySelector(
          "#player2Input label"
        ).textContent = `${players.player2.name}支付`;
        document.querySelector(
          "#player3Input label"
        ).textContent = `${players.player3.name}支付`;
        document.querySelector(
          "#player4Input label"
        ).textContent = `${players.player4.name}支付`;
      }

      // 显示通知
      function showNotification(message, type = "success") {
        notificationText.textContent = message;

        // 设置通知样式
        if (type === "success") {
          notification.classList.remove("bg-danger", "text-white");
          notification.classList.add("bg-success", "text-white");
          notificationIcon.className = "fa fa-check-circle mr-2";
        } else {
          notification.classList.remove("bg-success", "text-white");
          notification.classList.add("bg-danger", "text-white");
          notificationIcon.className = "fa fa-exclamation-circle mr-2";
        }

        // 显示通知
        notification.classList.remove("translate-x-full", "opacity-0");
        notification.classList.add("translate-x-0", "opacity-100");

        // 3秒后隐藏通知
        setTimeout(() => {
          notification.classList.remove("translate-x-0", "opacity-100");
          notification.classList.add("translate-x-full", "opacity-0");
        }, 3000);
      }

      // 切换表单显示
      equalBtn.addEventListener("click", () => {
        equalForm.classList.remove("hidden");
        unequalForm.classList.add("hidden");
      });

      unequalBtn.addEventListener("click", () => {
        unequalForm.classList.remove("hidden");
        equalForm.classList.add("hidden");
      });

      // 监听赢家选择框变化
      unequalWinner.addEventListener("change", () => {
        const winner = unequalWinner.value;
        player1Input.style.display = winner === "player1" ? "none" : "grid";
        player2Input.style.display = winner === "player2" ? "none" : "grid";
        player3Input.style.display = winner === "player3" ? "none" : "grid";
        player4Input.style.display = winner === "player4" ? "none" : "grid";
      });

      // 添加均等支付记录
      addEqualRecord.addEventListener("click", () => {
        const winner = document.getElementById("equalWinner").value;
        const amount = parseFloat(document.getElementById("equalAmount").value);

        if (isNaN(amount) || amount <= 0) {
          showNotification("请输入有效的金额", "error");
          return;
        }

        // 获取其他三个玩家
        const otherPlayers = Object.keys(players).filter(
          (player) => player !== winner
        );

        // 更新玩家余额
        players[winner].balance += amount * 3;
        otherPlayers.forEach((player) => {
          players[player].balance -= amount;
        });

        // 添加记录
        const record = {
          id: Date.now(),
          type: "equal",
          winner,
          amount,
          timestamp: new Date().toLocaleString(),
        };

        records.push(record);
        updateRecordList();
        updateResultDisplay();
        clearEqualForm();
        showNotification("记录已添加");
      });

      // 添加不同金额支付记录
      addUnequalRecord.addEventListener("click", () => {
        const winner = document.getElementById("unequalWinner").value;
        const player1Amount =
          parseFloat(document.getElementById("player1Amount").value) || 0;
        const player2Amount =
          parseFloat(document.getElementById("player2Amount").value) || 0;
        const player3Amount =
          parseFloat(document.getElementById("player3Amount").value) || 0;
        const player4Amount =
          parseFloat(document.getElementById("player4Amount").value) || 0;

        // 获取其他三个玩家
        const otherPlayers = Object.keys(players).filter(
          (player) => player !== winner
        );

        // 确保其他三个玩家的金额都已输入
        const hasInvalidAmount = otherPlayers.some((player) => {
          const amount = parseFloat(
            document.getElementById(`${player}Amount`).value
          );
          return isNaN(amount) || amount < 0;
        });

        if (hasInvalidAmount) {
          showNotification("请为所有支付玩家输入有效的金额", "error");
          return;
        }

        // 更新玩家余额
        const totalAmount = otherPlayers.reduce((sum, player) => {
          const amount = parseFloat(
            document.getElementById(`${player}Amount`).value
          );
          return sum + amount;
        }, 0);
        players[winner].balance += totalAmount;

        otherPlayers.forEach((player) => {
          const amount = parseFloat(
            document.getElementById(`${player}Amount`).value
          );
          players[player].balance -= amount;
        });

        // 添加记录
        const record = {
          id: Date.now(),
          type: "unequal",
          winner,
          amounts: {
            player1: otherPlayers.includes("player1") ? player1Amount : 0,
            player2: otherPlayers.includes("player2") ? player2Amount : 0,
            player3: otherPlayers.includes("player3") ? player3Amount : 0,
            player4: otherPlayers.includes("player4") ? player4Amount : 0,
          },
          totalAmount,
          timestamp: new Date().toLocaleString(),
        };

        records.push(record);
        updateRecordList();
        updateResultDisplay();
        clearUnequalForm();
        showNotification("记录已添加");
      });

      // 清空均等支付表单
      function clearEqualForm() {
        document.getElementById("equalAmount").value = "";
      }

      // 清空不同金额支付表单
      function clearUnequalForm() {
        document.getElementById("player1Amount").value = "";
        document.getElementById("player2Amount").value = "";
        document.getElementById("player3Amount").value = "";
        document.getElementById("player4Amount").value = "";
      }

      // 更新记录列表
      function updateRecordList() {
        if (records.length === 0) {
          recordList.innerHTML = `
                    <tr class="text-center">
                        <td colspan="6" class="px-6 py-10 text-gray-500">暂无记录</td>
                    </tr>
                `;
          return;
        }

        recordList.innerHTML = "";

        records.forEach((record) => {
          const row = document.createElement("tr");
          row.className = "hover:bg-gray-50 transition-colors";

          // 类型
          const typeCell = document.createElement("td");
          typeCell.className = "px-6 py-4 whitespace-nowrap";
          typeCell.innerHTML =
            record.type === "equal"
              ? '<span class="px-2 py-1 text-xs font-medium bg-primary/10 text-primary rounded-full">均等支付</span>'
              : '<span class="px-2 py-1 text-xs font-medium bg-secondary/10 text-secondary rounded-full">不同金额支付</span>';

          // 赢家
          const winnerCell = document.createElement("td");
          winnerCell.className = "px-6 py-4 whitespace-nowrap";
          winnerCell.textContent = players[record.winner].name;

          // 支付情况
          const paymentCell = document.createElement("td");
          paymentCell.className = "px-6 py-4";

          if (record.type === "equal") {
            // 获取其他三个玩家
            const otherPlayers = Object.keys(players).filter(
              (player) => player !== record.winner
            );
            const paymentText = otherPlayers
              .map((player) => `${players[player].name}: ¥${record.amount}`)
              .join("，");
            paymentCell.textContent = paymentText;
          } else {
            // 获取其他三个玩家
            const otherPlayers = Object.keys(players).filter(
              (player) => player !== record.winner
            );
            const paymentText = otherPlayers
              .map(
                (player) =>
                  `${players[player].name}: ¥${record.amounts[player]}`
              )
              .join("，");
            paymentCell.textContent = paymentText;
          }

          // 总金额
          const totalCell = document.createElement("td");
          totalCell.className = "px-6 py-4 whitespace-nowrap font-medium";
          totalCell.textContent = `¥${
            record.type === "equal" ? record.amount * 3 : record.totalAmount
          }`;

          // 时间
          const timeCell = document.createElement("td");
          timeCell.className =
            "px-6 py-4 whitespace-nowrap text-sm text-gray-500";
          timeCell.textContent = record.timestamp;

          // 操作
          const actionCell = document.createElement("td");
          actionCell.className =
            "px-6 py-4 whitespace-nowrap text-right text-sm font-medium";

          const deleteBtn = document.createElement("button");
          deleteBtn.className =
            "text-danger hover:text-danger/80 transition-colors";
          deleteBtn.innerHTML = '<i class="fa fa-trash mr-1"></i> 删除';
          deleteBtn.addEventListener("click", () => deleteRecord(record.id));

          actionCell.appendChild(deleteBtn);

          // 添加所有单元格到行
          row.appendChild(typeCell);
          row.appendChild(winnerCell);
          row.appendChild(paymentCell);
          row.appendChild(totalCell);
          row.appendChild(timeCell);
          row.appendChild(actionCell);

          // 添加行到表格
          recordList.appendChild(row);
        });
      }

      // 删除记录
      function deleteRecord(id) {
        const recordIndex = records.findIndex((record) => record.id === id);

        if (recordIndex === -1) return;

        const record = records[recordIndex];

        // 恢复玩家余额
        if (record.type === "equal") {
          players[record.winner].balance -= record.amount * 3;

          // 获取其他三个玩家
          const otherPlayers = Object.keys(players).filter(
            (player) => player !== record.winner
          );
          otherPlayers.forEach((player) => {
            players[player].balance += record.amount;
          });
        } else {
          players[record.winner].balance -= record.totalAmount;

          // 获取其他三个玩家
          const otherPlayers = Object.keys(players).filter(
            (player) => player !== record.winner
          );
          otherPlayers.forEach((player) => {
            if (record.amounts[player]) {
              players[player].balance += record.amounts[player];
            }
          });
        }

        // 删除记录
        records.splice(recordIndex, 1);
        updateRecordList();
        updateResultDisplay();
        showNotification("记录已删除");
      }

      // 更新结果显示
      function updateResultDisplay() {
        Object.keys(players).forEach((player) => {
          const resultElement = document.getElementById(`${player}Result`);
          const balance = players[player].balance;

          resultElement.textContent = `¥${balance.toFixed(2)}`;

          // 设置颜色
          if (balance > 0) {
            resultElement.className = "text-xl font-semibold text-success";
          } else if (balance < 0) {
            resultElement.className = "text-xl font-semibold text-danger";
          } else {
            resultElement.className = "text-xl font-semibold text-gray-500";
          }
        });
      }

      // 清空所有记录
      clearRecords.addEventListener("click", () => {
        if (records.length === 0) {
          showNotification("没有记录可清空");
          return;
        }

        if (confirm("确定要清空所有记录吗？此操作不可撤销。")) {
          // 重置玩家余额
          Object.keys(players).forEach((player) => {
            players[player].balance = 0;
          });

          // 清空记录
          records = [];
          updateRecordList();
          updateResultDisplay();
          showNotification("所有记录已清空");
        }
      });

      // 导出结果
      exportResult.addEventListener("click", () => {
        if (records.length === 0) {
          showNotification("没有记录可导出", "error");
          return;
        }

        // 准备导出数据
        let exportData = "麻将记钱结果导出\n\n";

        // 添加玩家结算结果
        exportData += "结算结果：\n";
        Object.keys(players).forEach((player) => {
          const balance = players[player].balance;
          exportData += `${players[player].name}: ${
            balance >= 0 ? "赢" : "输"
          } ¥${Math.abs(balance).toFixed(2)}\n`;
        });

        exportData += "\n\n详细记录：\n";
        exportData += "类型\t赢家\t支付情况\t总金额\t时间\n";

        // 添加详细记录
        records.forEach((record) => {
          const winnerName = players[record.winner].name;

          if (record.type === "equal") {
            // 获取其他三个玩家
            const otherPlayers = Object.keys(players).filter(
              (player) => player !== record.winner
            );
            const paymentText = otherPlayers
              .map((player) => `${players[player].name}: ¥${record.amount}`)
              .join("，");
            const totalAmount = record.amount * 3;

            exportData += `均等支付\t${winnerName}\t${paymentText}\t¥${totalAmount}\t${record.timestamp}\n`;
          } else {
            // 获取其他三个玩家
            const otherPlayers = Object.keys(players).filter(
              (player) => player !== record.winner
            );
            const paymentText = otherPlayers
              .map(
                (player) =>
                  `${players[player].name}: ¥${record.amounts[player]}`
              )
              .join("，");

            exportData += `不同金额支付\t${winnerName}\t${paymentText}\t¥${record.totalAmount}\t${record.timestamp}\n`;
          }
        });

        // 创建并下载文件
        const blob = new Blob([exportData], {
          type: "text/plain;charset=utf-8",
        });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = `麻将记钱结果_${new Date().toLocaleDateString()}.txt`;
        link.click();

        showNotification("结果已导出");
      });

      // 修改昵称
      updateNicknames.addEventListener("click", () => {
        // 检查昵称是否重复
        if (checkDuplicateNicknames()) {
          return;
        }

        players.player1.name = player1Nickname.value.trim() || "玩家1";
        players.player2.name = player2Nickname.value.trim() || "玩家2";
        players.player3.name = player3Nickname.value.trim() || "玩家3";
        players.player4.name = player4Nickname.value.trim() || "玩家4";

        player1Name.textContent = players.player1.name;
        player2Name.textContent = players.player2.name;
        player3Name.textContent = players.player3.name;
        player4Name.textContent = players.player4.name;

        // 更新选择框和标签
        updatePlayerNamesInSelects();

        updateRecordList();
        updateResultDisplay();
        showNotification("昵称已更新");
      });

      // 初始化显示
      updatePlayerNamesInSelects();
      updateRecordList();
      updateResultDisplay();
    </script>
  </body>
</html>
